package com.fjc.authorcation;

import com.fjc.dao.SysUserMapper;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;


/**
 * 自定义密码验证
 * Created by fjc on 2018/9/24.
 */
@Component
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {
    @Autowired
    private SysUserMapper sysUserMapper;

    private Cache<String, AtomicInteger> passwordRetryCache;

    public CustomCredentialsMatcher(CacheManager cacheManager) {
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        //可以查到user对象，拿到加密的salt，所以这边可以自定义实现加盐加密
        System.out.println(sysUserMapper.selectByPrimaryKey(1));

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String password = String.valueOf(usernamePasswordToken.getPassword());
        String dataPwd = (String)getCredentials(info);
        String username = token.getPrincipal().toString();

        // retry count + 1
        AtomicInteger retryCount = passwordRetryCache.get(username);
        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }
        if (retryCount.incrementAndGet() > 3) {
            // if retry count > 5 throw
            throw new ExcessiveAttemptsException();
        }

        boolean matches = equals(password,dataPwd);
        if (matches) {
            // clear retry count
            passwordRetryCache.remove(username);
        }
        return matches;
    }
}
